# -*- coding: utf-8 -*-

#使用Python的Playwright库创建新的浏览器上下文以实现测试隔离，包括：处理多标签页、新窗口及弹出窗口


from playwright.sync_api import sync_playwright

if __name__ == '__main__':
    ##浏览器上下文

    #一个浏览器同时打开2个页签
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False, slow_mo=1000)
        context = browser.new_context()  # 创建上下文，浏览器实例1

        page1 = context.new_page()  # 打开标签页1
        page2 = context.new_page()  # 打开标签页2
        page1.goto("https://www.baidu.com/")
        #page1.fill('#kw', "第一个页签搜索内容")
        #page1.wait_for_timeout(3000)

        page2.goto("https://www.baidu.com/")
        #page2.fill('#kw', "第二个页签搜索内容")
        #page2.wait_for_timeout(3000)


        #处理新标签页
        with context.expect_page() as new_page_info:
            page2.click('text=新闻')  # 又打开了一个新的标签也
        new_page = new_page_info.value
        new_page.wait_for_load_state()  # 等待页面加载到指定状态
        print(new_page.title())

        #处理弹出窗口
        # with new_page.expect_popup() as popup_info:
        #     new_page.get_by_text("open the popup").click()
        # popup = popup_info.value
        # popup.wait_for_load_state()
        # print(popup.title())



    #同时操作多个浏览器，不会共享cookies,适用于多用户登录
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False, slow_mo=1000)
        context1 = browser.new_context()  # 创建上下文，浏览器实例1
        context2 = browser.new_context()  # 创建上下文，浏览器实例2
        #操作第一个浏览器窗口
        page1 = context1.new_page()    # 打开标签页
        page1.goto("https://www.baidu.com/")

        # 操作第二个浏览器窗口
        page2 = context2.new_page()  # 打开标签页
        page2.goto("https://www.baidu.com/")
